package com.zmx.patientend.fragment.order;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.wang.adapters.interfaceabstract.OnItemClickListener;
import com.zmx.patientend.R;
import com.zmx.patientend.adapter.OrderManagementAdapter;
import com.zmx.patientend.okhttp.OkHttp3ClientManager;
import com.zmx.patientend.pojo.OrderInfo;
import com.zmx.patientend.pojo.OrderProduct;
import com.zmx.patientend.pojo.Paging;
import com.zmx.patientend.utils.AllUtil;
import com.zmx.patientend.view.activity.GoodsOrderDetailsActivity;
import com.zmx.patientend.view.util.CustomToast;
import com.zmx.patientend.view.util.MySharedPreferences;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 程序猿：胖胖祥
 * 时 间：2020/12/25  12:26
 * 功 能：以发货
 */
public class ForTheOrderFragment extends Fragment {

    private OrderManagementAdapter adapter;
    private List<OrderInfo> lists;
    private RecyclerView recyclerView;

    private ImageView empty_image;
    private Paging paging = new Paging();
    private SmartRefreshLayout refreshLayout;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_orders, container, false);


        lists = new ArrayList<>();
        recyclerView = view.findViewById(R.id.recyclerView);
        adapter = new OrderManagementAdapter(this.getActivity());
        recyclerView.setLayoutManager(new LinearLayoutManager(ForTheOrderFragment.this.getContext()));
        recyclerView.setAdapter(adapter);
        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            protected void onItemClick(View view, int listPosition) {

                Intent intent = new Intent();
                intent.putExtra("orderNumber", lists.get(listPosition).getId() + "");
                intent.putExtra("state", lists.get(listPosition).getState() + "");
                intent.setClass(ForTheOrderFragment.this.getContext(), GoodsOrderDetailsActivity.class);
                startActivity(intent);

            }
        });
        empty_image = view.findViewById(R.id.empty_image);


        // 开启自动加载功能
        refreshLayout = view.findViewById(R.id.refreshLayout);
        refreshLayout.autoRefresh();
        refreshLayout.setEnableAutoLoadMore(true);
        refreshLayout.setOnRefreshListener(refreshLayout -> {

            lists.clear();
            paging.setPageNow(1);
            getOrderList();

        });

        refreshLayout.setOnLoadMoreListener(refreshLayout -> {

            if (paging.getPageNow() < paging.getPageCount()) {

                paging.setPageNow(paging.getPageNow() + 1);
                getOrderList();

            } else {

                refreshLayout.finishLoadMore(true);
                CustomToast.getInstance().showToastCustom(ForTheOrderFragment.this.getContext(), "没有更多数据啦!", Gravity.BOTTOM);

            }

        });


        return view;

    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler(){

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            switch (msg.what){

                case 1:

                    try {

                        JSONObject object = new JSONObject(msg.obj.toString());

                        if (object.getInt("code") == 1){

                            empty_image.setVisibility(View.GONE);
                            JSONArray data = object.getJSONArray("data");
                            paging.setPageCount(object.getInt("count"));
                            Gson gson = new Gson();
                            for (int i = 0;i<data.length();i++){

                                OrderInfo oi = gson.fromJson(data.getJSONObject(i).toString(),OrderInfo.class);

                                JSONArray detailed = new JSONArray(data.getJSONObject(i).getString("detailed"));
                                List<OrderProduct> ops = new ArrayList<>();
                                for (int j=0;j<detailed.length();j++){

                                    OrderProduct op = gson.fromJson(detailed.getJSONObject(j).toString(),OrderProduct.class);
                                    ops.add(op);

                                }

                                oi.setLists(ops);
                                lists.add(oi);


                            }

                            adapter.setListAndNotifyDataSetChanged(lists);
                            if (paging.getPageNow() == 1) {

                                refreshLayout.finishRefresh(true);

                            } else {

                                refreshLayout.finishLoadMore(true);

                            }
                        }else{

                            refreshLayout.finishRefresh(true);
                            empty_image.setVisibility(View.VISIBLE);

                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        Log.e("异常","异常"+e.toString());
                    }

                    break;

            }

        }
    };

    public void getOrderList() {

        List<String> ls = new ArrayList<>();
        ls.add(paging.getPageSize() + "");
        ls.add(paging.getPageNow() + "");
        ls.add("4");
        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(ls)));
        params.put("token", MySharedPreferences.getInstance(ForTheOrderFragment.this.getContext()).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(ForTheOrderFragment.this.getContext()).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "getOrderList");
        params.put("data[state]", "4");
        params.put("data[row]", paging.getPageNow());
        params.put("data[number]", paging.getPageSize());
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/mall/", params, handler, 1, 404);

    }

    //签名
    public String sing(List<String> list) {

        StringBuilder requestparams = new StringBuilder();
        requestparams.append(MySharedPreferences.getInstance(this.getContext()).getString(MySharedPreferences.uid, "") +
                MySharedPreferences.getInstance(this.getContext()).getString(MySharedPreferences.role, "") +
                System.currentTimeMillis() / 1000 + MySharedPreferences.getInstance(this.getContext()).getString(MySharedPreferences.password, ""));

        if (list != null) {
            for (String s : list) {
                requestparams.append(s);
            }
        }
        return requestparams.toString();

    }
}
